package cn.zwk.handler;

import cn.zwk.entity.*;
import cn.zwk.resolver.MetricListText;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class CounterHandler extends MetricHandler {

    public CounterHandler() {
        super.type = "counter";
    }

    @Override
    public MetricList buildMetric(MetricListText metricListText) {
        String[] lines = metricListText.getText().split("\n");
        List<AbstractItem> items = new ArrayList<>();
        StringBuilder annotationBuilder = new StringBuilder();
        int si = metricListText.getSi();
        for (int i = 0; i < si; i++) {
            annotationBuilder.append(lines[i]);
            annotationBuilder.append("\n");
        }
        for (int i = si; i < lines.length; i++) {
            MetricItem item = parseMetricLine(lines[i]);
            if (item != null) {
                items.add(item);
            }
        }
        
        MetricList metricList = new MetricList();
        metricList.setAnnotation(annotationBuilder.toString());
        metricList.setName(metricListText.getName());
        metricList.setType(metricListText.getType());
        metricList.setItems(items);
        return metricList;
    }
    
    private MetricItem parseMetricLine(String line) {
        DataRow dataRow = parseRow(line);
        if (dataRow != null) {
            MetricItem item = new MetricItem();
            item.setRow(dataRow);
            return item;
        }
        return null;
    }

    @Override
    public void next(AbstractItem item) {
        if (item instanceof MetricItem metricItem) {
            DataRow row = metricItem.getRow();
            if (row != null) {
                // Counter类型：增长值为上一次的1~1.5倍
                double currentVal = row.getVal();
                double growthFactor = 1.0 + Math.random() * 0.5; // 1.0 到 1.5
                double newVal = currentVal * growthFactor+Math.random();
                row.setVal(newVal);
            }
        }
    }
}
